package com.example.javaee_blog.utils;

import com.example.javaee_blog.constants.Constant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtils {
    private final static long EXPIRATION = 60 * 60 * 1000;
    private final static String secret = "4D/Rz5VUTxK/wifB5CWsvoaUkeO1cCEKdikYQ9oqUDc=";
    private final static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));


    public static String getToken(Map<String, Object> claim){
        //decode -> 编码
        return Jwts.builder().setClaims(claim)
                .signWith(key) //设置签名
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRATION)) //设置过期时间
                .compact();
    }

//    public void getKey(){
//        //生成key
//        SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
//        //encode -> 解码
//        String encode = Encoders.BASE64.encode(secretKey.getEncoded());
//        System.out.println(encode);
//    }
    public static Claims parseToken(String token){
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims body = null;
        try {
            body = build.parseClaimsJws(token).getBody();
        } catch (Exception e){
            log.error("验证错误,token:{}",token);
        }
        return body;
    }
    public static Integer getUserIdFromToken(String token){
        Claims body = parseToken(token);
        if(body != null){
            return (Integer) body.get(Constant.USER_ID);
        }
        return null;
    }
    public static boolean checkToken(String token){
        Claims body = parseToken(token);
        if(body == null)
            return false;
        return true;
    }
}
